package app.kotlin_1.sql

import android.content.Context
import app.kotlin_1.gen.DaoMaster
import app.kotlin_1.gen.DaoSession
import org.greenrobot.greendao.AbstractDaoSession
import org.greenrobot.greendao.query.QueryBuilder

/**
 * Created by 刘智强 on 2017/9/26.
 * 建立数据库连接和初始化
 *
 */
class SQLiteManager {
    private var context: Context? = null

    private constructor(context: Context?) {
        this.context = context
    }

    companion object {
        private val DB_NAME = "GameDataBase"
        private var instance: SQLiteManager? = null
        private var daoMaster: DaoMaster? = null
        private var daoHelp: DaoMaster.OpenHelper? = null
        private var daoSession: DaoSession? = null

        /**
         * 单例模式
         */
        fun getInstangce(c: Context): SQLiteManager {
            if (instance == null) {
                synchronized(SQLiteManager::class.java) {
                    instance = SQLiteManager(c)

                }
            }

            return instance!!

        }
    }

    /**
     * 获取daomaster的实体
     */
    fun getDaoMaster() {


    }

    /**
     * 获取daosession的实体
     */
    fun getDaoSession():DaoSession {
        if (daoMaster == null) {
            daoHelp = DaoMaster.DevOpenHelper(context, DB_NAME, null)
            daoMaster = DaoMaster(daoHelp?.writableDb)
        }
        if (daoSession == null) {
            daoSession = daoMaster?.newSession()

        }
        return  daoSession!!
    }

    /**
     * 允许输出greendao的日志信息

     */
    fun setDebug() {
        QueryBuilder.LOG_SQL = true
        QueryBuilder.LOG_VALUES = true
    }

    /**
     * 关闭数据库连接
     */
    fun closeConnection() {
        closeHelp()
        closeSession()


    }

    private fun closeHelp() {
        if (daoHelp != null) {
            daoHelp?.close()
            daoHelp = null
        }

    }

    private fun closeSession() {
        if (daoSession != null) {
            daoSession?.clear()
            daoSession = null
        }

    }


}